package com.example.contacter

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View

class IndexView : View {
    interface Listener {
        fun selected(char: String)
    }

    var listener: Listener? = null
    private val words = arrayOf(
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
        "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    )

    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context)
    }

    private var itemWidth = 0
    private var itemHeight = 0
    private var paint: Paint? = null
    private fun initView(context: Context) {
        paint = Paint()
        paint?.textSize = DensityUtil.dip2px(context, 12F).toFloat()
        paint?.textAlign = Paint.Align.CENTER
        setBackgroundColor(Color.RED)
        paint?.isAntiAlias = true //抗锯齿
        paint?.typeface = Typeface.DEFAULT_BOLD
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        itemWidth = measuredWidth
        itemHeight = measuredHeight / words.size
    }

    private var touchIndex: Int = -1
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val rect = Rect()
        paint?.getTextBounds(words.toString(), 0, 1, rect)
        //字母的高和宽
        val wordWidth = rect.width()
        val wordHeight = rect.height()

        for (i in 0 until words.size) {
            if (touchIndex == i) {
                paint?.color = Color.RED
            } else {
                paint?.color = Color.WHITE
            }
            val wordStartY = i * itemHeight + itemHeight / 2 + wordHeight / 2
            val wordStartX = itemWidth / 2 - wordWidth / 2 + 5
            canvas?.drawText(words[i], wordStartX.toFloat(), wordStartY.toFloat(), paint!!)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN,
            MotionEvent.ACTION_MOVE -> {
                Log.w("IndexView", "MotionEvent.ACTION_MOVE")
                var index: Int = (event.y / itemHeight).toInt()
                if (index < 0) {
                    index = 0
                }
                if (index >= words.size) {
                    index = words.size - 1
                }

                if (index != touchIndex) {
                    touchIndex = index
                    invalidate()
                    listener?.selected(words[touchIndex])
                }
            }
            MotionEvent.ACTION_UP -> {
                Log.w("IndexView", "MotionEvent.ACTION_UP")
                touchIndex = -1
                invalidate()
            }
        }
        return true
    }
}